#ifndef TIMER_H
#define TIMER_H

#include <p89lpc9351.h>
#include "motor.h"

//fire every 100 us
#define TIMER_FREQ 10000L
#define XTAL 7062000L
//The reload value formula comes from the datasheet...
#define TIMER0_RELOAD_VALUE (65536L-((XTAL)/(2*TIMER_FREQ)))

// time elapsed since start, in milliseconds
static volatile long millis = 0;
volatile char pwmCount = 0;

void InitClock()
{
    // Initialize timer 0 for ISR 'pwmcounter' below
    TR0=0; // Stop timer 0
    TF0=0; // Clear the overflow flag
    TMOD=(TMOD&0xf0)|0x01; // 16-bit timer
    TH0=TIMER0_RELOAD_VALUE/0x100;
    TL0=TIMER0_RELOAD_VALUE%0x100;
    TR0=1; // Start timer 0
    ET0=1; // Enable timer 0 interrupt
    EA=1;  // Enable global interrupts

    millis = 0;
}

//Interrupt 1 is for timer 0. Controls PWM of motors as well.
void timerupdate (void) interrupt 1 using 1
{
    TF0 = 0; // Clear the overflow flag
    //Reload the timer
    TR0 = 0; // Stop timer 0
    TH0 = TIMER0_RELOAD_VALUE/0x100;
    TL0 = TIMER0_RELOAD_VALUE%0x100;
    TR0 = 1; // Start timer 0

    if(++pwmCount > 99) 
        pwmCount = 0;
    MOTOR_LEFT_OUT = (lspeed > pwmCount) ? 1 : 0;
    MOTOR_RIGHT_OUT = (rspeed > pwmCount) ? 1 : 0;

    if (pwmCount % 10 == 0)
        ++millis;
}

unsigned int getSecs()
{
    return millis/1000;
}

unsigned long getMillis()
{
    return millis;
}

char getDiff()
{
    static unsigned long oldTime = millis;
    char diff = millis - oldTime;
    oldTime = millis;
    return diff;
}

void delay(int t)
{
    long start = millis;
    while (millis - start < t) {}
}

// delays 100-200 us
void delaySmall()
{
    // need to do twice to guarantee 100 us delay at least
    char startCount = pwmCount;
    while (startCount == pwmCount) {}
    startCount = pwmCount;
    while (startCount == pwmCount) {}
}

#endif